#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "driver/uart.h"
#include "soc/uart_struct.h"
#include "uart2.h"
#include "string.h"
#include "spp_task.h"
#include "spp_command_process.h"
#include "esp_log.h"

#define UART_TAG "uart2"
#define UART_USED UART_NUM_2
#define ring_data_len() ((RecvHead + sizeof(RecvBuff) - RecvTail) % sizeof(RecvBuff))
#define ring_next_index(tail,target) (((tail) + (target)) % sizeof(RecvBuff))

#define ringbuf_add_data(data,len) do\
    {\
		if(len > 0)\
	    {\
	      for(int i=0;i<len;i++)\
	      {\
	        RecvBuff[RecvHead] = data[i];\
	        RecvHead = (RecvHead + 1) % sizeof(RecvBuff);\
	      }\
	    }\
    }while(0);

#define ring_cpy_data(buf,len,head) do\
	{\
		for(int i=0;i<(len);i++)\
		  {\
			buf[i] = RecvBuff[head];\
			head = ring_next_index(head ,1);\
		  }\
	}while(0);

uint8_t RecvBuff[1024];
uint8_t ProtocalBuff[1024];
static uint16_t cur_recv_index = 0;
uint16_t RecvHead;
uint16_t RecvTail;
uint8_t tmpbuff[128];

void Cmd_ReportImg(void *v, int a) ;
void uart2_thread()
{
	const int uart_num = UART_USED;
	int len = 0;
	RecvHead = RecvTail = 0;
    ESP_LOGI(UART_TAG, "uart2 thread start");
	while(true)
	{
		len = uart_read_bytes(uart_num, tmpbuff, 127, (100 / portTICK_RATE_MS));
        if (len > 0) {
    		ringbuf_add_data(tmpbuff,len);
            ESP_LOGI(UART_TAG, "uart2 recv len : %d", len);
			Cmd_ReportImg(tmpbuff, 0);
        }
        // while (ring_data_len() > 0) {
        //     uint8_t u8Data = RecvBuff[RecvTail];
        //     RecvTail = ring_next_index(RecvTail, 1);
        //     set_send_port(UART_PORT_SEND);
        //     if (spp_get_cmd(u8Data, ProtocalBuff, &cur_recv_index) == E_TRUE) {
        //         ssp_command_process(ProtocalBuff, UART_PORT_SEND);
        //     }
        // }
     }
}
void initialise_uart(void)
{
    #define BUF_SIZE 1024
	const int uart_num = UART_USED;
	uart_config_t uart_config = {
		.baud_rate = 115200,
		.data_bits = UART_DATA_8_BITS,
		.parity = UART_PARITY_DISABLE,
		.stop_bits = UART_STOP_BITS_1,
		.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		.rx_flow_ctrl_thresh = 122,
	};

	// Configure UART parameters
	uart_param_config(uart_num, &uart_config);
	// Set UART1 pins(TX: IO23, RX: I022, RTS: IO18, CTS: IO19)
	uart_set_pin(uart_num, 17, 16, -1, -1);

	// Install UART driver (we don't need an event queue here)
	// In this example we don't even use a buffer for sending data.
	uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0);
	// Set RS485 half duplex mode
	uart_set_mode(uart_num, UART_MODE_UART);

	xTaskCreate(uart2_thread, "uart2_thread", 4096, NULL, 10, NULL);
}


